/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DatabaseAccessing;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;



/**
 *
 * @author MaramZahran
 */

public class UserModelController
{


 public Customer  getUserByEmail(String email,String password)
    {
       // SessionFactory sessionFact=new Configuration().configure().buildSessionFactory();
        Session  session=SessionFactoryUtil.getInstance();   //sessionFact.openSession();

        // Criterion email=Restrictions.eq("customerName", userName);

        Criteria cr=session.createCriteria(Customer.class).add(Restrictions.eq("customerEmail", email)).add(Restrictions.eq("passwordHash", password));
        //cr.add(email);
        Customer cust=(Customer)cr.uniqueResult();

        return cust;

       /*
        String queryStr=" from Customer where customername=:name or passwordHash=:password ";
        Query queryRslt=session.createQuery(queryStr).setString("name", userName).setString("password", password);

        Iterator rslt=queryRslt.list().iterator();
        if(rslt.hasNext())
        {
           //
            return  true;
        }
        return null;
        */
    }
    /**
     *
     * @param userName
     * @param password
     * user to get user or to validate login user
     * @return Customers
     */

    public Customer  getUser(String userName,String password)
    {
       // SessionFactory sessionFact=new Configuration().configure().buildSessionFactory();
        Session  session=SessionFactoryUtil.getInstance();   //sessionFact.openSession();

        // Criterion email=Restrictions.eq("customerName", userName);

        Criteria cr=session.createCriteria(Customer.class).add(Restrictions.eq("customerName", userName)).add(Restrictions.eq("passwordHash", password));
        //cr.add(email);
        Customer cust=(Customer)cr.uniqueResult();

        return cust;

       /*
        String queryStr=" from Customer where customername=:name or passwordHash=:password ";
        Query queryRslt=session.createQuery(queryStr).setString("name", userName).setString("password", password);

        Iterator rslt=queryRslt.list().iterator();
        if(rslt.hasNext())
        {
           //
            return  true;
        }
        return null;
        */
    }
    /**
     *
     * This function override for get user take only id
     * and return customer
     * @param id
     *
     * @return customer
     */
public Customer  getUser(int id)
    {
       // SessionFactory sessionFact=new Configuration().configure().buildSessionFactory();
        Session  session=SessionFactoryUtil.getInstance();   //sessionFact.openSession();

        // Criterion email=Restrictions.eq("customerName", userName);

        String queryStr=" from Customer where customerID="+id+"";  // get customer by id

        Query queryRslt=session.createQuery(queryStr);

        Iterator rslt=queryRslt.list().iterator();
        if(rslt.hasNext())
           return (Customer)rslt.next();

        return new Customer();
        

    }




    /**
     *
     * @param cust
     * edit customers with data in the customer parameter
     * @throws AddUserException
     */

    public void editProfile(Customer c) throws AddUserException
    {
         //SessionFactory sessionFact=new Configuration().configure().buildSessionFactory();

        Session  session=SessionFactoryUtil.getInstance();

        String queryStr=" from Customer where (customername='"+c.getCustomerName()+"' or customerEmail='"+c.getCustomerEmail()+"') and customerID !="+c.getCustomerId()+"";

        Query queryRslt=session.createQuery(queryStr);

        Iterator rslt=queryRslt.list().iterator();

        if(rslt.hasNext())
        {
            Customer cust=(Customer)rslt.next();
            if(cust.getCustomerName().equals(c.getCustomerName()) && cust.getCustomerEmail().equals(c.getCustomerEmail()) )
                        throw new AddUserException("User Name and Email used Please select another name", 0);
            if(cust.getCustomerName().equals(c.getCustomerName()))
                 throw new AddUserException("User Name used Please select another name", 1);
            if(cust.getCustomerEmail().equals(c.getCustomerEmail()))
                throw new AddUserException("Email used Please select another name", 2);

        }

        session.flush();
        //Customer customers=new Customer();
        //customers=  (Customer)session.load(Customer.class,6);//=c;
        Customer customers=c;
        if(customers ==null)
        {
            customers=new Customer();
            customers.setCustomerId(c.getCustomerId());
        }
        //customers=copyCustomers(c);
        //customers.setCustomerId(c.getCustomerId());
        session.clear();
        session.beginTransaction();
        session.update(customers);
        session.getTransaction().commit();
        //customers=null;
        //c=null;
        session.clear();
        session.flush();
    
    }


    /**
     * This function used to return list of all
     * customers to draw then into table in jsp page
     * or any class
     * @return List<Customer>
     */
    public List<Customer> loadAllCustomer()
    {
       Session session=SessionFactoryUtil.getInstance(); //get session

       String queryStr=" from Customer "; //select all customers

        Query queryRslt=session.createQuery(queryStr); // create query that return all cutomers

        return  queryRslt.list(); // represent data into list and return it
    }




    /**
     * This function used to remove customers from database
     * accept id as parameter and return boolean that determine if customer
     * remove or not
     * @param id
     * @return boolean
     */
    public boolean removeCustomer(int id)
    {
        Session session=SessionFactoryUtil.getInstance();
        session.beginTransaction();
        session.delete(getUser(id));
        session.getTransaction().commit();
        session.clear();
        return true;
        //session.delete();

    }
   /**
    *
    * @param cust
    * copy customer into template customers and return it
    * 
    * @return
    */
   public Customer copyCustomers(Customer cust)
   {
        Customer customers=new Customer();
        //customers.setCustomerId(cust.getCustomerId());
        customers.setCredit(cust.getCredit());
        customers.setCustomerName(cust.getCustomerName());
        customers.setPasswordHash(cust.getPasswordHash());
        customers.setPhoneNumber(cust.getPhoneNumber());
        customers.setCustomerEmail(cust.getCustomerEmail());
        return customers;
   }

     /**
     *
     * @param c
     * @throws AddUserException
     * used to insert user in database
     * before insert it check if name in database or Not
     *
     */

    public void addNewConstumer(Customer c) throws AddUserException
    {
        
 //        SessionFactory sessionFact=new Configuration().configure().buildSessionFactory();

        Session  session=SessionFactoryUtil.getInstance();                    //sessionFact.openSession();
 
        String queryStr=" from Customer where customername='"+c.getCustomerName()+"' or customerEmail='"+c.getCustomerEmail()+"' ";

        Query queryRslt=session.createQuery(queryStr);

        Iterator rslt=queryRslt.list().iterator();

        if(rslt.hasNext())
        {
            Customer cust=(Customer)rslt.next();
            if(cust.getCustomerName().equals(c.getCustomerName()) && cust.getCustomerEmail().equals(c.getCustomerEmail()) )
                        throw new AddUserException("User Name and Email used Please select another name", 0);
            if(cust.getCustomerName().equals(c.getCustomerName()))
                 throw new AddUserException("User Name used Please select another name", 1);
            if(cust.getCustomerEmail().equals(c.getCustomerEmail()))
                throw new AddUserException("Email used Please select another name", 2);

        }

        Customer customers=new Customer();

        customers=copyCustomers(c);

        session.beginTransaction();
        session.persist(customers);
        session.getTransaction().commit();
        
    }




























































    public ArrayList<TransactionData> getTransaction(int id)
    {
       // SessionFactory sessionFact=new Configuration().configure().buildSessionFactory();
       Session  session=SessionFactoryUtil.getInstance();   //sessionFact.openSession();

        //List<TransactionData> transactionData=new List<TransactionData>();
        ArrayList<TransactionData> transactionsData=new ArrayList<TransactionData>();

        String queryStr=" select t.transactionID as transid,c.customername as name , t.date as dat ,p.productName as proname  from  `transaction` t , `customer` c ,`products` p where"

         +"  t.customerID="+id+" and t.customerID=c.customerID and t.productID=p.productID ";  // get customer by id

        Query queryRslt=session.createSQLQuery(queryStr).addScalar("transid", Hibernate.INTEGER)
              .addScalar("name",Hibernate.STRING).addScalar("dat",Hibernate.DATE).addScalar("proname",Hibernate.STRING);

        Iterator iterator=queryRslt.list().iterator();
        while(iterator.hasNext())
        {
        Object [] obj=(Object [])iterator.next();

        TransactionData trans=new TransactionData();

       trans.setCustomerName(obj[1].toString());
       trans.setDate(obj[2].toString());
       trans.setTransactionId(new Integer(obj[0].toString()));
       trans.setProductName(obj[3].toString());
       transactionsData.add(trans);
        }


       // Object [] obj=(Object [])queryRslt.uniqueResult();

      // transactionData.setCustomerName(obj[1].toString());
      // transactionData.setDate(new Date(obj[2].toString()));
      // transactionData.setTransactionId(new Integer(obj[0].toString()));
      // transactionData.setProductName(obj[3].toString());


       return transactionsData;
    }

  


}
